package com.mzba.easy.weibo.widget;

import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Html;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.mzba.easy.weibo.BasicActivity;
import com.mzba.easy.weibo.R;
import com.mzba.easy.weibo.db.CommentEntry;
import com.mzba.easy.weibo.db.EmotionField;
import com.mzba.easy.weibo.ui.GridViewAdapter;
import com.mzba.easy.weibo.util.AppContext;
import com.mzba.easy.weibo.util.BasicUIEvent;
import com.mzba.easy.weibo.util.UICore;
import com.mzba.easy.weibo.util.WeiboManager;

public class CommentsTimelineView extends LinearLayout implements BasicUIEvent, Callback {
	
	private Context context;
	private CommentEntry entry;
	private WeiboManager weiboManager;
	private Handler handler;
	private boolean isRetweet = false;
	
	public static final int DESTROYDIALOG = 0x00000101;
	private static final int reply_comment = 0x00000102;
	private static final int reply_comment_error = 0x00000103;
	private static final int delete = 0x00000104;
	private static final int delete_error = 0x000005;
	
	private View CommentTimelineItem;
	private View commentItem;
	private LinearLayout preView;
	public CustomDialog dialog;
	public IPhoneDialog.Builder alert = null;
	public boolean alertIsShow = false;
	
	ImageButton emotionView;
	ImageView retweetView;
	LinearLayout retweetSelectLayout;
	Button commentView;
	EditText editView;
	LinearLayout bodyLayout;
	
	private LayoutParams params;
	private PopupWindow pop;

	public CommentsTimelineView(Context context, CommentEntry entry) {
		super(context);
		this.context = context;
		this.entry = entry;
		weiboManager = new WeiboManager(context);
		handler = new Handler(this);
		this.setOrientation(LinearLayout.VERTICAL);
		try {
			initWidget();
		} catch (Exception e) {
			e.printStackTrace();
		}
		this.addView(CommentTimelineItem);
		params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		params.leftMargin = 35;
		
		View view = LayoutInflater.from(context).inflate(R.layout.emotion_gridview, null);
		GridView gridView = (GridView) view.findViewById(R.id.emotion_gridview);
		GridViewAdapter gridAdapter = new GridViewAdapter(context);
		gridView.setAdapter(gridAdapter);
		pop = new PopupWindow(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		ColorDrawable dw = new ColorDrawable(-00000);
		pop.setBackgroundDrawable(dw);
		pop.update();
		gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
				try {
					pop.dismiss();
					EmotionField filed = AppContext.getInstance().getEmotionFields().get(arg2);
					editView.append(filed.getPhrase());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}
	
	public CommentsTimelineView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public CommentsTimelineView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}
	
	private void initWidget() throws Exception {
		ViewHolder holder = null;
		CommentTimelineItem = LayoutInflater.from(context).inflate(R.layout.comments_timeline_item, null);
		holder = new ViewHolder();
		holder.avatarView = (RemoteImageView) CommentTimelineItem.findViewById(R.id.iv_author_photo);
		holder.textView = (CustomTextView) CommentTimelineItem.findViewById(R.id.comments_timeline_text);
		holder.sourceView = (TextView) CommentTimelineItem.findViewById(R.id.commemnts_timeline_from);
		holder.deleteView = (TextView) CommentTimelineItem.findViewById(R.id.comments_timeline_delete);
		holder.replyView = (TextView) CommentTimelineItem.findViewById(R.id.comments_timeline_reply);
		holder.replyTextView = (TextView) CommentTimelineItem.findViewById(R.id.comments_timeline_reply_text);
		holder.replyLayout = (LinearLayout) CommentTimelineItem.findViewById(R.id.comments_timeline_reply_layout);
		holder.avatarView.setDefaultImage(R.drawable.avatar_default_big);
		holder.avatarView.setImageUrl(entry.getUser().getProfile_image_url());
//		String username = "<font color=#419AD9>" + entry.getUser().getScreen_name() + ":" + "</font>";
//		Spanned str = Html.fromHtml(username + "&nbsp;" + entry.getText() + "(" + DateUtil.getCreateAt(entry.getCreated_at()) + ")");
//		holder.textView.setText(str);
		String username = entry.getUser().getScreen_name() + ":" + "&nbsp;";
		holder.textView.setText(entry.getText(), username, AppContext.getInstance().getFaceMap());
		holder.sourceView.setText(Html.fromHtml("来自" + entry.getSource()));
//		TextAutoLink.addURLSpan(str.toString(), holder.textView);
		if (AppContext.getInstance().getUid().equals(entry.getUser().getId())) {
			holder.replyLayout.setVisibility(View.GONE);
		} else {
			holder.replyLayout.setVisibility(View.VISIBLE);
		}
		if (entry.getReply_comment() != null) {
			holder.replyTextView.setText(Html.fromHtml("回复我的评论:&nbsp;" + "<font color=#419AD9>" + entry.getReply_comment().getText() + "</font"));
		} else {
			holder.replyTextView.setText(Html.fromHtml("评论我的微博:&nbsp;" + "<font color=#419AD9>" + entry.getStatus().getText() + "</font"));
		}
		holder.replyView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (preView == null) {
					createCommentItemView();
					CommentsTimelineView.this.addView(commentItem, params);
					commentItem.setVisibility(View.VISIBLE);
				} else {
					if (preView == CommentsTimelineView.this) {
						if (commentItem.isShown()) {
							CommentsTimelineView.this.removeView(commentItem);
							commentItem.setVisibility(View.GONE);
						} else {
							CommentsTimelineView.this.addView(commentItem, params);
							commentItem.setVisibility(View.VISIBLE);
						}
					} else {
						preView.removeView(commentItem);
						commentItem.setVisibility(View.GONE);
						CommentsTimelineView.this.addView(commentItem, params);
						commentItem.setVisibility(View.VISIBLE);
					}
				}
				preView = CommentsTimelineView.this;
				editView.setText("回复@" + entry.getUser().getScreen_name() + ":");
				editView.setFocusable(true);
				editView.setFocusableInTouchMode(true);
			}
		});
		
		holder.deleteView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				setSysMes("确定要删除该评论吗？", delete);
			}
		});
	}
	
	
	private void createCommentItemView() {
		commentItem = LayoutInflater.from(context).inflate(R.layout.timeline_comment_item, null);
		editView = (EditText) commentItem.findViewById(R.id.timeline_comment_edit);
		emotionView = (ImageButton) commentItem.findViewById(R.id.timeline_comment_emotion);
		retweetView = (ImageView) commentItem.findViewById(R.id.timeline_comment_retweet_select);
		retweetSelectLayout = (LinearLayout) commentItem.findViewById(R.id.timeline_comment_retweet_select_layout);
		commentView = (Button) commentItem.findViewById(R.id.timeline_comment_comment);
		bodyLayout = (LinearLayout) commentItem.findViewById(R.id.timeline_comment_body_layout);
		
		commentView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loading();
				String content = editView.getText().toString().trim();
				Object[] objs = new Object[4];
				objs[0] = content;
				objs[1] = entry.getStatus().getId();
				objs[2] = entry.getId();
				objs[3] = isRetweet == true ? 1 : 0;
				UICore.eventTask(CommentsTimelineView.this, (BasicActivity) context, reply_comment, "", objs); 
			}
		});
		
		retweetSelectLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (isRetweet) {
					isRetweet = false;
					retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_unselect);
				} else {
					isRetweet = true;
					retweetView.setBackgroundResource(R.drawable.btn_comment_sametime_select);
				}
			}
		});
		emotionView.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (!pop.isShowing()) {
					pop.showAtLocation(commentItem, Gravity.BOTTOM, 0, 0);
				} else {
					pop.dismiss();
				}
			}
		});
	}
	
	public static class ViewHolder {
		RemoteImageView avatarView;
		CustomTextView textView;
		TextView replyTextView;
		TextView sourceView;
		TextView deleteView;
		TextView replyView;
		LinearLayout replyLayout;
	}

	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case reply_comment:
			Object[] objs2 = (Object[]) obj;
			CommentEntry commentEntry2 = weiboManager.replayCommemnt(objs2[0].toString(), objs2[1].toString(), objs2[2].toString(),
					Integer.parseInt(objs2[3].toString()));
			if (commentEntry2 != null) {
				handler.sendEmptyMessage(reply_comment);
			} else {
				handler.sendEmptyMessage(reply_comment_error);
			}
			break;
		case delete:
			CommentEntry entry3 = weiboManager.destroyComment(entry.getId());
			if (entry3 != null) {
				handler.sendEmptyMessage(delete);
			} else {
				handler.sendEmptyMessage(delete_error);
			}
			break;
		default:
			break;
		}
	}

	public void loading() {
		try {
			if (dialog == null || !dialog.isShowing()) {
				View progressview = LayoutInflater.from(context)
						.inflate(R.layout.progress_dialog, null);
				CustomDialog.Builder progressBuilder = new CustomDialog.Builder(context);
				progressBuilder.setContentView(progressview);
				dialog = progressBuilder.create();
				dialog.show();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void destroyDialog() {
		handler.sendEmptyMessage(DESTROYDIALOG);
	}
	
	public void onToast(String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_LONG).show();
	}

	/**
	 * 系统信息 必须在handler或者控件触发 调用才有效
	 * 
	 * @param message
	 */
	public void setSysMes(String message, final int what) {
		if (message == null || "出错了".equals(message)) {
			return;
		}
		if (dialog != null && dialog.isShowing()) {
			dialog.cancel();
		}
		if (alert == null)
			alert = new IPhoneDialog.Builder(context);

		if (!alertIsShow) {
			alertIsShow = true;
			alert.setTitle(context.getString(R.string.system_info));
			alert.setMessage(message)
				.setNegativeButton(context.getString(R.string.confirm_cancel),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							alertIsShow = false;
						}
					})
			.setPositiveButton(context.getString(R.string.confirm_ok),
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							sysMesPositiveButtonEvent(what);
							alertIsShow = false;
						}
					});
			alert.create().show();
		}
	}
	
	public void sysMesPositiveButtonEvent(int what) {
		if (what == delete) {
			UICore.eventTask(this, (BasicActivity) context, delete, "", null); 
		}
	}
	
	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case reply_comment:
			onToast("评论成功");
			break;
		case reply_comment_error:
			onToast("评论失败");
			break;
		case delete:
			onToast("删除成功");
			break;
		case delete_error:
			onToast("删除失败");
			break;
		default:
			break;
		}
		return false;
	}

}
